package com.rc.saas.mini.controller.format.qrcode;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.fluent.Request;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;

/**
 * @author wangzhengwei
 * @create 2021/5/11
 */
public class BcQrCodeFormat extends QrCodeFormat {
    private static Logger logger = LogManager.getLogger(BcQrCodeFormat.class);

    @Override
    public String getGunNoByQrCode(String qrCode) {
        return notify(qrCode);
    }


    public String notify(String qrCode) {
        //是否包含 &connectorSn=
        //https://chonger.i100c.com/stationapi/station/identifyQR?code=397528953&equipmentSn=5023201201001&connectorSn=5023200101
        if (!qrCode.contains("&connectorSn=")) {
            return null;
        }
        //推送地址
        String URL = qrCode + "&type=jz";

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            logger.info(":BcQrCodeFormat 加密明文:{}", URL);
            return Request.Post(URL)
                    .connectTimeout(3000)
                    .execute()
                    .handleResponse(new ResponseHandler<String>() {
                        @Override
                        public String handleResponse(HttpResponse httpResponse) throws IOException {
                            int code = httpResponse.getStatusLine().getStatusCode();
                            logger.info("BcQrCodeFormat 发送:{},:{}", code, URL);

                            if (code == 200) {
                                HttpEntity entity = httpResponse.getEntity();
                                String result = EntityUtils.toString(entity, "UTF-8");
                                logger.info(":BcQrCodeFormat response,:{},:{}", result, URL);

                                if (StringUtils.isBlank(result)) {
                                    return null;
                                }
                                JSONObject jsonObject = JSONObject.parseObject(result);
                                String end = (String) JSONObject.parseObject(jsonObject.get("data").toString()).get("ConnectorID");
                                return end;
                            } else {
                                return null;
                            }
                        }
                    });

        } catch (Exception e) {
            logger.error("BcQrCodeFormat 报错", e.getMessage());
        }
        return null;
    }
}